/**
 * This file is a part of qloudgen-sec. 
 * You can redistribute qloudgen-sec and/or modify it under the terms of the Lesser GNU General Public License version 3. 
 * qloudgen-sec is distributed WITHOUT ANY WARRANTY. 
 *
 * See the Lesser GNU General Public License for more details at http://www.gnu.org/licenses/. 
 **/
package org.qloudgen.sec.cas.support.user.userdetail.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

import org.qloudgen.sec.cas.support.user.services.UserDetail;
import org.qloudgen.sec.cas.support.user.services.UserDetailManager;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public final class ManageUserDetailSimpleFormController extends SimpleFormController {
	private static final Logger logger = LoggerFactory.getLogger(ManageUserDetailSimpleFormController.class);

    /** Instance of ServiceRegistryManager. */
    @NotNull
    private final UserDetailManager userDetailManager;


    public ManageUserDetailSimpleFormController(final UserDetailManager userDetailManager) {
        this.userDetailManager = userDetailManager;
    }

    /**
     * 
     */
    @Override
    protected void initBinder(final HttpServletRequest request,
            final ServletRequestDataBinder binder) throws Exception {
        binder.setRequiredFields(new String[] { "colName","label","colLength"});
        //binder.setDisallowedFields(new String[] {"id"});
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    /**
     *
     */
    @Override
    protected ModelAndView onSubmit(final HttpServletRequest request,
            final HttpServletResponse response, final Object command,
            final BindException errors) throws Exception {
        UserDetail userDetail = (UserDetail) command;
        // only change object class if there isn't an explicit RegisteredService class set
        
        this.userDetailManager.save(userDetail);
        logger.debug("Saved changes to userDetail " + userDetail.getId());

        final ModelAndView modelAndView = new ModelAndView(new RedirectView(
                "manageUserDetail.html#" + userDetail.getId(), true));
        modelAndView.addObject("action", "add");
        modelAndView.addObject("id", userDetail.getId());

        return modelAndView;
    }

    @Override
    protected Object formBackingObject(final HttpServletRequest request)
            throws Exception {
        final String id = request.getParameter("id");

        if (!StringUtils.hasText(id)) {
            
            final Object userDetail;
            if (this.getCommandClass() != null) {
                userDetail = this.createCommand();
            } else {
                userDetail = new UserDetail();
                //((User)user).setId("this is test");
            }
            logger.debug("Created new userDetail " + userDetail.toString());
            return userDetail;
        }

        final UserDetail userDetail = this.userDetailManager.findUserDetailBy(id);

        if (userDetail != null) {
            logger.debug("userDetail is  " + userDetail.getId());
        } else {
            logger.debug("Invalid userDetail id specified.");
        }

        return userDetail;
    }

    /**

     */
    @Override
    protected Map<?, ?> referenceData(final HttpServletRequest request) throws Exception {

        final Map<String, Object> model = new HashMap<String, Object>();

        model.put("pageTitle", getFormView());
        model.put("commandName", getCommandName());
        return model;
    }
}

